using System;
using System.Data;
using System.Data.OleDb;

namespace MushManager.DAL
{
	public class DALOleDbEngine : DALEngine
	{
		public DALOleDbEngine(string connectionString) : base(connectionString)
		{
		}
	
		protected override IDbConnection GetConnection()
		{
			OleDbConnection newConn = new OleDbConnection(ConnectionString);
			newConn.Open();
			
			return newConn;
		}
		
		protected override IDbCommand CreateCommand(string spName)
		{
			OleDbCommand cmd = new OleDbCommand(spName, (OleDbConnection)Connection);
			cmd.CommandType = CommandType.StoredProcedure;
		
			foreach (DALParameter param in Parameters)
			{
				OleDbParameter sqlParam  = new OleDbParameter(param.Name, param.Value);
				sqlParam.Direction       = param.Direction;				
				sqlParam.Value           = param.Value;
								
				cmd.Parameters.Add(sqlParam);
				
				if (param.Size != 0)
				{
					sqlParam.Size   = param.Size;
					sqlParam.DbType = param.Type;
				}	
			}
	
			return cmd;
		}

		public override void ExecSP_DataSet(string spName, DataSet dataSet, string tableName)
		{
			try
			{
				IDbCommand cmd = CreateCommand(spName);				
				OleDbDataAdapter adapter = new OleDbDataAdapter((OleDbCommand)cmd);
				adapter.Fill(dataSet, tableName);
									
			}
			catch (Exception e)
			{				
				throw new DALException("Error in DALOleDbEngine::ExecSP_DataSet, in stored procedure '" + spName + "'", e);
			}		
		}
		
		public override void ExecQuery_DataSet(string query, DataSet dataSet, string tableName)
		{		
			try
			{			
				OleDbDataAdapter adapter = new OleDbDataAdapter(query, (OleDbConnection)Connection);	
				adapter.Fill(dataSet, tableName);
									
			}
			catch (Exception e)
			{				
				throw new DALException("Error in DALOleDbEngine::ExecQuery_DataSet, in query '" + query + "'", e);
			}		
		
		}	
	}
}